#include <iostream>  
#include <vector>  
#include <string>  
  
// 获取KMP算法的next数组  
std::vector<int> getNext(const std::string& pattern) {  
    int m = pattern.size();  
    std::vector<int> next(m, 0);  
    int len = 0;  
    int i = 1;  
      
    while (i < m) {  
        if (pattern[i] == pattern[len]) {  
            len++;  
            next[i] = len;  
            i++;  
        } else {  
            if (len != 0) {  
                len = next[len - 1];  
            } else {  
                next[i] = 0;  
                i++;  
            }  
        }  
    }  
    return next;  
}  
  
int countNonOverlappingInstances(const std::string& text, const std::string& pattern) {  
    int n = text.size();  
    int m = pattern.size();  
    std::vector<int> next = getNext(pattern);  
    int count = 0;  
    int i = 0, j = 0;  
      
    while (i < n) {  
        if (pattern[j] == text[i]) {  
            i++;  
            j++;  
        }  
        if (j == m) {  
            count++;  
            j = next[j - 1];  
        } else if (i < n && pattern[j] != text[i]) {  
            if (j != 0) {  
                j = next[j - 1];  
            } else {  
                i++;  
            }  
        }  
    }  
    return count;  
}  
  
int main() {  
    std::string text = "abcabcabcabc";  
    std::string pattern = "abc";  
    std::cout << "Number of non-overlapping instances of pattern in text: " << countNonOverlappingInstances(text, pattern) << std::endl;  
    return 0;  
}
